﻿/*-----------------------------------------------
// File: ServerTimerTool.cs 
// Description: 用于时间的方法，主要用于与服务器时间同步。
// 这里要注意时区的问题，与服务器通讯一律使用的时间为UTC时间。 
-----------------------------------------------*/
using UnityEngine;
using System.Collections;


public class ServerTimerTool
{
    const long begin = 621355968000000000;
    private static long distance = 0;
    private static long time_zone = 0;
    /// <summary>
    /// 与服务器同步时间
    /// </summary>
    /// <param name="serverTime"></param>
    public static void CorrectTime(long serverTime)
    {
        distance = Java2CSTime(serverTime).Ticks - System.DateTime.UtcNow.Ticks;
        time_zone = System.DateTime.Now.Ticks - System.DateTime.UtcNow.Ticks;
    }
    /// <summary>
    /// 当前时间，时区为格林威治时区
    /// </summary>
    public static System.DateTime CurrentUTCTime
    {
        get
        {
            return new System.DateTime(System.DateTime.UtcNow.Ticks + distance);
        }
    }
    /// <summary>
    /// 当前时间，时区为当前时区
    /// </summary>
    public static System.DateTime CurrentTime
    {
        get
        {
            return new System.DateTime(System.DateTime.Now.Ticks + distance);
        }
    }
    /// <summary>
    /// Java To CSharp Time.
    /// </summary>
    /// <param name="time">Java Time(UTC)</param>
    /// <returns>CSharp DateTime(UTC)</returns>
    public static System.DateTime Java2CSTime(long time)
    {
        return new System.DateTime(time * 10000 + begin);
    }

    public static System.DateTime Java2CSTimeLocale(long time)
    {
        return new System.DateTime(time * 10000 + begin + time_zone);
    }

    /// <summary>
    /// CSharp To Java Time
    /// </summary>
    /// <param name="t">CSharp DateTime</param>
    /// <returns>Java Time</returns>
    public static long CSTime2Java(System.DateTime t)
    {
        return (t.Ticks - begin) / 10000;
    }


    /// <summary>
    /// JAVA下的当前UTC时间
    /// </summary>
    /// <returns>Java Current UTC Time</returns>
    public static long CurrentUTCJavaTime()
    {
        return CSTime2Java(CurrentUTCTime);
    }
    /// <summary>
    /// Java下的当前时区时间
    /// </summary>
    /// <returns>Java Current TimeZone Time</returns>
    public static long CurrentJavaTime()
    {
        return CSTime2Java(CurrentTime);
    }

    public static long ClientJavaTime()
    {
        return (System.DateTime.Now.Ticks - begin) / 10000;
    }

    public static long ClientUtcJavaTime()
    {
        return (System.DateTime.UtcNow.Ticks - begin) / 10000;
    }

    public static long UnixTime()
    {
        return (System.DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
    }


}
